import * as Cesium from 'cesium';
import { CzmViewer } from "xbsj-xe2/dist-node/xe2-cesium-objects";
import { ESBoxEntity } from "./ESBoxEntity";
import { CzmESObjectWithLocation } from "esobjs-xe2-plugin/dist-node/esobjs-xe2-plugin-main";
import { toColor } from "xbsj-renderer/dist-node/xr-cesium";
//ESBoxEntity对象的实现类
export class CzmESBoxEntity extends CzmESObjectWithLocation<ESBoxEntity> {

    static readonly type = this.register(ESBoxEntity.type, this);

    constructor(sceneObject: ESBoxEntity, czmViewer: CzmViewer) {
        super(sceneObject, czmViewer);
        const viewer = czmViewer.viewer;
        if (!viewer) {
            console.warn(`viewer is undefined!`);
            return;
        }
        const entities = viewer.entities;

        let boxEnt: Cesium.Entity | undefined;


        const position = () => {
            return Cesium.Cartesian3.fromDegrees(...(sceneObject.position ?? [0, 0, 0]));
        }


        {//创建
            const createEntity = (position: Cesium.Cartesian3) => {
                const ent = entities.add({
                    show: sceneObject.show,
                    position,
                    box: {
                        dimensions: new Cesium.Cartesian3(...sceneObject.size),
                        material: toColor(sceneObject.color),
                    },
                });
                return ent;
            }
            const pos = position();
            boxEnt = createEntity(pos);
        }

        //对象销毁时移除对象
        this.d(() => {
            boxEnt && entities.remove(boxEnt);
            boxEnt = undefined;
        });



        {//position
            const updatePosition = () => {
                //@ts-ignore
                boxEnt && (boxEnt.position = position());
            }
            this.d(sceneObject.positionChanged.don(updatePosition));
        }


        {//show控制
            const updateShow = () => { boxEnt && (boxEnt.show = sceneObject.show); };
            this.d(sceneObject.showChanged.don(updateShow));
        }

        {//属性变化
            const update = () => {
                //@ts-ignore
                boxEnt && boxEnt.box && (boxEnt.box.dimensions = new Cesium.Cartesian3(...sceneObject.size));
                //@ts-ignore
                boxEnt && boxEnt.box && (boxEnt.box.material = toColor(sceneObject.color));
            };
            this.d(sceneObject.sizeChanged.don(update));
            this.d(sceneObject.colorChanged.don(update));
        }

        { //flyTo
            this.d(sceneObject.flyToEvent.don(() => {
                boxEnt && viewer.flyTo(boxEnt);
            }));
        }
    }
}
